// 链式地址
class HashMapChaining {
    #size: number; //键值对数量
    #capcity: number; // 哈希表容量
    #loadThres: number; // 触发扩容的负载因子
    #extendRatio: number; // 扩容倍数
    #buckets: Pair[][]; // 桶数组

    constructor() {
        this.#size = 0;
        this.#capcity = 4;
        this.#loadThres = 2.0 / 3.0;
        this.#extendRatio = 2;
        this.#buckets = new Array(this.#capcity).fill(null).map((x) => []);
    }

    // 哈希函数
    #hashFunc(key: number): number {
        return key % this.#capcity;
    }

    // 计算负载因子
    #loadFactor(): number {
        return this.#size / this.#capcity;
    }

    get(key: number): string | null {
        const index = this.#hashFunc(key);
        const bucket = this.#buckets[index];
        for (const pair of bucket) {
            if (pair.key === key) {
                return pair.val;
            }
        }
        return null;
    }

    put(key: number, val: string): void {
        // 当负载因子超过阈值时，执行扩容
        if (this.#loadFactor() > this.#loadThres) {
            this.#extend()
        }
        const index = this.#hashFunc(key);
        const bucket = this.#buckets[index];
        for (const pair of bucket) {
            if (pair.key === key) {
                pair.val = val;
                return;
            }
        }
        const pair = new Pair(key, val);
        bucket.push(pair);
        this.#size++;
    }

    // 扩容
    #extend() {
        // 暂存原始哈希表
        const bucketsTmp = this.#buckets;
        // 初始化扩容后的新哈希表
        this.#capcity *= this.#extendRatio;
        this.#buckets = new Array(this.#capcity).fill(null).map(x => []);
        this.#size = 0;
        // 将键值对从原哈希表迁移至新哈希表
        for(const bucket of bucketsTmp) {
            for (const pair of bucket) {
                this.put(pair.key, pair.val);
            }
        }
    }

    remove(key: number) {
        const index = this.#hashFunc(key);
        const bucket = this.#buckets[index];
        // 遍历桶，从中删除键值对
        for (let i = 0; i < bucket.length; i++) {
            if (bucket[i].key === key) {
                bucket.splice(i, 1);
                this.#size--;
                break;
            }

        }
    }

    // 打印哈希表
    print(): void {
        for (const bucket of this.#buckets) {
            const res = [];
            for (const pair of bucket) {
                res.push(pair.key + ' ->' + pair.val);
            }
            console.log(res);
        }
    }
}